package cn.ch.org.service.impl;

import cn.ch.basic.service.impl.BaseServiceImpl;
import cn.ch.basic.util.MD5Utils;
import cn.ch.basic.util.StrUtils;
import cn.ch.org.domain.Employee;
import cn.ch.org.mapper.EmployeeMapper;
import cn.ch.org.service.IEmployeeService;
import cn.ch.user.domain.Logininfo;
import cn.ch.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)//配置事物
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    /**
     * 覆写下面的方法实现级联调整，联级添加
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        initEmployee(employee);//初始化employee
        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(employee.getId());
        employeeMapper.save(employee);

    }
    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);//设置盐值
        employee.setSalt(salt);//盐值
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);//使用盐值 加密 密码
        employee.setPassword(md5Pwd);//设置密码
    }

    /**
     *联级修改
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        Long id = employee.getId();//根据id进行修改
        Logininfo logininfo = employee2logininfo2(employee);
        logininfoMapper.update(logininfo);
        employee.setLogininfo_id(employee.getId()); //获取外键
        employeeMapper.update(employee);
    }
    private Logininfo employee2logininfo2(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setId(employee.getLogininfo_id());//设置对应id
        logininfo.setType(0);
        return logininfo;
    }

    /**
     * 联级删除
     * @param id
     */
    @Override
    public void remove(Long id) {
        employeeMapper.delete(id);
        Employee employee = employeeMapper.loadById(id);
        logininfoMapper.delete(employee.getLogininfo_id());
    }

    /**
     *查询店铺派出去的接单人
     * @param shopId
     * @return
     */
    @Override
    public List<Employee> queryByShopId(Long shopId) {
        return employeeMapper.loadByShopId(shopId);
    }
}
